/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.jkeepass.util;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.DefaultMutableTreeNode;

import com.l2fprod.gui.plaf.skin.SkinLookAndFeel;
import com.l2fprod.util.OS;
import com.thoughtworks.xstream.XStream;

import de.renier.jkeepass.JKeePass;
import de.renier.jkeepass.Messages;
import de.renier.jkeepass.elements.BasicElement;
import de.renier.jkeepass.elements.BasicElementList;
import de.renier.jkeepass.elements.ContainerElement;
import de.renier.jkeepass.elements.Element;
import de.renier.jkeepass.encryption.Cryptor;
import de.renier.jkeepass.encryption.Cryptor.CryptionException;


/**
 * Utils
 *
 * @author <a href="mailto:software@renier.de">Renier Roth</a>
 */
public class Utils {
  

  private static final int LAST_OPENFILE_COUNT = 4;
  
  private static FileFilter passFileFilter = null;
  
  /**
   * isEmpty
   * 
   * @param input
   * @return
   */
  public static boolean isEmpty(String input) {
    if (input != null && input.length() > 0) {
      return false;
    }
    return true;
  }
  
  /**
   * getLastOpenedFiles
   *
   * @return
   */
  public static List getLastOpenedFiles() {
    List files = new LinkedList();
    for (int i = 0; i < LAST_OPENFILE_COUNT;i++) {
      String lastfile = LocalProperties.getInstance().getProperty(LocalProperties.PROP_LASTFILE_PREFIX + i);
      if (!Utils.isEmpty(lastfile)) {
        files.add(new File(lastfile));
      }
    }
    return files;
  }
  
  /**
   * setLastOpenedFile
   *
   * @param file
   */
  public static void setLastOpenedFile(File file) {
    List files = getLastOpenedFiles();
    // remove preview existing file
    files.remove(file);
    // add last file on top of list
    files.add(0,file);
    // save to LocalProperties
    Iterator it = files.iterator();
    int counter = 0;
    while (it.hasNext()) {
      // break if we reache maximum
      if (counter == LAST_OPENFILE_COUNT) {
        break;
      }
      // store filepath to property
      File tempFile = (File)it.next(); 
      LocalProperties.getInstance().setProperty(LocalProperties.PROP_LASTFILE_PREFIX + counter,tempFile.getAbsolutePath());
      counter++;
    }
    // store properties
    LocalProperties.getInstance().storeLocalProps();
  }
  
  /**
   * getPassFileFilter
   *
   * @return
   */
  public static synchronized FileFilter getPassFileFilter() {
    if (passFileFilter == null) {
      passFileFilter = new FileFilter() {
        public boolean accept(File f) {
          if (f.isDirectory()) {
            return true;
          }
          if (f.getName().endsWith(".pass")) { //$NON-NLS-1$
            return true;
          }
          return false;
        }
        public String getDescription() {
          return Messages.getString("Utils.1"); //$NON-NLS-1$
        }
      };
    }
    
   return passFileFilter;
  }
  
  /**
   * outputNode
   */
  public static void outputNode(OutputStream out, DefaultMutableTreeNode node) throws CryptionException {
    XStream xtream = new XStream();
    String data = xtream.toXML(node);
    Cryptor.encryptText(out, data);
  }
  
  public static void outputNodeUnencrypted(OutputStream out, DefaultMutableTreeNode node) {
    XStream xtream = new XStream();
    xtream.toXML(node, out);
  }  
  
  /**
   * readNode
   */
  public static DefaultMutableTreeNode readNode(InputStream in) throws CryptionException {
    XStream xtream = new XStream();
    return (DefaultMutableTreeNode)xtream.fromXML(Cryptor.decryptText(in));
//    return (DefaultMutableTreeNode)xtream.fromXML((new CryptReader(new GZIPInputStream(in))).read());
//    return (DefaultMutableTreeNode)xtream.fromXML((new CryptReader(in)).read());
  }
  
  /**
   * initMetalWTahomaTheme
   */
  public static void initDefaultTheme() {
    try {
//      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); //$NON-NLS-1$
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //$NON-NLS-1$
      UIManager.getLookAndFeelDefaults().put("ClassLoader", Utils.class.getClassLoader()); //$NON-NLS-1$
    } catch (Exception e) {
      e.printStackTrace();
    }
  }  
  
  /**
   * initSkinLFTheme
   */
  public static void initSkinLFTheme(String themepack) {
    try {
      URL mytheme = Utils.class.getResource("/de/renier/jkeepass/resources/themepacks/" + themepack); //$NON-NLS-1$
      if (mytheme != null) {
        SkinLookAndFeel.setSkin(SkinLookAndFeel.loadThemePack(mytheme));
        UIManager.setLookAndFeel(new SkinLookAndFeel());
      }
      UIManager.getLookAndFeelDefaults().put("ClassLoader", Utils.class.getClassLoader()); //$NON-NLS-1$
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * setSkin
   */
  public static void styleChange(String styleType) {
    try {
      if ("default".equals(styleType)) { //$NON-NLS-1$
        initDefaultTheme();
      } else {
        initSkinLFTheme(styleType);
      }
      if (Boolean.valueOf(LocalProperties.getInstance().getProperty(LocalProperties.PROP_SYSTEM_STYLE_DECORATE)).booleanValue()) {
        if (OS.isOneDotFourOrMore()) {
          java.lang.reflect.Method method = JFrame.class.getMethod("setDefaultLookAndFeelDecorated", //$NON-NLS-1$
                                                                   new Class[] { boolean.class });
          method.invoke(null, new Object[] { Boolean.TRUE });
          method = JDialog.class.getMethod("setDefaultLookAndFeelDecorated", new Class[] { boolean.class }); //$NON-NLS-1$
          method.invoke(null, new Object[] { Boolean.TRUE });
        }
      }

      // refresh
      if (JKeePass.application != null) {
        SwingUtilities.updateComponentTreeUI(JKeePass.application);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }  

  /**
   * Place a String on the clipboard, and make this class the
   * owner of the Clipboard's contents.
   */
   public static void setClipboardContents( String aString ){
     StringSelection stringSelection = new StringSelection( aString );
     Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
     clipboard.setContents( stringSelection, JKeePass.application );
   }

  public static void outputNodeContainerUnencrypted(FileOutputStream outFile, ContainerElement container) {
    BasicElementList elementList = container.getElements();
    Iterator it = elementList.iterator();
    while (it.hasNext()) {
      BasicElement element = (BasicElement)it.next();
      StringBuffer buffer = new StringBuffer();
      buffer.append((element).getUser()).append(" ").append((element).getPassword()).append('\n');
      try {
        outFile.write(buffer.toString().getBytes());
      } catch (IOException e) {
        // nothing
      }
    }
  }
}
